package com.zrwl.poscloud.xo.utils;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class GroovyExecutorUtil {
    private static final GroovyClassLoader CLASS_LOADER = new GroovyClassLoader();

    public static Object execute(String scriptText, String methodName, Map<String, Object> contextParams, Object... args)
            throws Exception {

        Class<?> groovyClass = CLASS_LOADER.parseClass(scriptText);
        GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
        if (contextParams != null && !contextParams.isEmpty()) {
            // 将map中的值设置为脚本属性，在脚本中可以直接调用
            contextParams.forEach(groovyObject::setProperty);
        }
        return groovyObject.invokeMethod(methodName, args);
    }
}
